import landsatxplore.api
from landsatxplore.earthexplorer import EarthExplorer


def request_Landsat(username, password, product, lat, lon, start_date, end_date, cloud_max):
    api = landsatxplore.api.API(username, password)

    scenes = api.search(
        dataset=product,
        latitude=lat,
        longitude=lon,
        start_date=start_date,
        end_date=end_date,
        max_cloud_cover=cloud_max)

    print('{} scenes found.'.format(len(scenes)))
    api.logout()
    return scenes


def download_landsat(username, password, Landsat_name, output_dir):
    Earth_Down = EarthExplorer(username, password)

    for scene in Landsat_name:
        # 下面代码将'entityId'改为'display_id'，因为两个id下载名称有差别：
        #        'entity_id': 'LC81960462015361LGN01',
        #        'display_id': 'LC08_L1TP_196046_20151227_20170331_01_T1'

        ID = scene['display_id']
        print('Downloading data %s ' % ID)
        # 下 if面这行代码将原来的scene_id 改为identifier，因为scene_id已被弃用
        #
        Earth_Down.download(identifier=ID, output_dir=output_dir)

    Earth_Down.logout()


if __name__ == '__main__':
    username = 'GISer2.5'
    password = '123456789GIS'

    # 下面所有6行代码，可以建立任意循环，以达到批量下载的目的，不赘述
    product = 'sentinel_2a'
    lat = 19.53
    lon = -1.53
    start_date = '2020-01-01'
    end_date = '2021-03-01'
    cloud_max = 10
    output_dir = r'H:\Lansat数据下载'
    Landsat_name = request_Landsat(username, password, product, lat, lon, start_date, end_date, cloud_max)
    # print(Landsat_name)

    download_landsat(username, password, Landsat_name, output_dir)